<?php

namespace app\admin\controller\service;

use app\common\controller\Backend;
use think\Db;
/**
 * 项目管理
 *
 * @icon fa fa-circle-o
 */
class Goods extends Backend
{

    /**
     * Goods模型对象
     * @var \app\admin\model\service\Goods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\service\Goods;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("isTravelList", $this->model->getIsTravelList());
        $this->view->assign("chooseSkillTypeList", $this->model->getChooseSkillTypeList());
        $this->view->assign("specTypeList", $this->model->getSpecTypeList());
        $this->view->assign("shopStateList", $this->model->getShopStateList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("toshopList", $this->model->getToshopList());
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->where($where)
            ->where('shop_id',0)
            ->order($sort, $order)
            ->paginate($limit);
        foreach ($list as &$value)
        {
            $value->categoryName = \app\admin\model\service\Category::where('id',$value->category_id)->value('name');
            $value->twoCategoryName = \app\admin\model\service\Category::where('id',$value->two_category_id)->value('name');
            $value->skillCateName = \app\api\model\service\SkillCate::getNameList($value->skill_cate_ids);
            $value->update_time = $value->updatetime?date("Y-m-d",$value->updatetime):'';
            $value->create_time = date("Y-m-d",$value->createtime);
        }
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        ($params['spec_type'] == 1 && !$params['spu']) && $this->error('请完善项目规格');
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        $result = false;
        if($params['city']){
            $address = explode('/',$params['city']);
            $params['province'] = $address[0];
            $params['city'] = $address[1];
            //$params['district'] = isset($address[1])?:'';
            $cityList = \app\admin\model\service\Cityconfig::column('city');
            !in_array($params['city'],$cityList) && $this->error('当前城市未开通');
        }else{
            unset($params['city']);
        }

        Db::startTrans();
        try {
            $params['shop_state'] = 1;
            $goods = new \app\admin\model\service\Goods ($params);
            $goods->allowField(true)->save();
            $result = true;

            if($params['spec_type'] == 1)
            {
                $spuList = json_decode($params['spu'],true);

                $spu = [];

                foreach ($spuList as $value) {

                    $spu[] = [
                        'goods_id'	=> $goods->id,
                        'name'		=> $value['name'],
                        'skudetail'=> implode(',',array_column($value['info'],'name'))
                    ];
                }

                if(!model('\app\admin\model\service\Goodsspu')->allowField(true)->saveAll($spu)){
                    $result == false;
                }

                $skuList = json_decode($params['sku'],true);
                foreach ($skuList  as $value) {

                    $sku[] = [
                        'goods_id' 		=> $goods->id,
                        'name' 	        => $value['name'],
                        'cost_seconds'  => $value['cost_seconds'],
                        'price' 		=> $value['price'],
                    ];
                }

                if(!model('\app\admin\model\service\Goodssku')->allowField(true)->saveAll($sku)){
                    $result == false;
                }
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }
    
    public function edit($ids = null){
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $spu = \app\admin\model\service\Goodsspu::where(['goods_id'=>$row->id,'status'=>'normal'])->field('name,skudetail')->select();
            foreach ($spu as &$item){
                $info = explode(',',$item['skudetail']);
                $arr=[];
                foreach ($info as $val){
                    $v['name'] = $val;
                    array_push($arr,$v);
                }
                $item['info'] = $arr;
            }
            $row->city = $row->province.'/'.$row->city;
            $sku = \app\admin\model\service\Goodssku::where(['goods_id'=>$row->id,'status'=>'normal'])->field('name,price,cost_seconds')->select();
            $this->assignconfig('spu',$spu);
            $this->assignconfig('sku',$sku);
            $this->assignconfig('spec_type',$row['spec_type']);
            $this->assignconfig('choose_skill_type',$row['choose_skill_type']);
            $this->assignconfig('status',$row['status']);
            $this->view->assign("row", $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        $result = false;
        if($params['city'])
        {
            $address = explode('/',$params['city']);
            $params['province'] = $address[0];
            $params['city'] = $address[1];
            //$params['district'] = isset($address[1])?:'';
            $cityList = \app\admin\model\service\Cityconfig::column('city');
            !in_array($params['city'],$cityList) && $this->error('当前城市未开通');
        }else{
            unset($params['city']);
        }
        Db::startTrans();
        try {
            $goods = new \app\admin\model\service\Goods ();
            $goods->allowField(true)->save($params,['id'=>$row->id]);
            $result = true;
            if($params['status'] == 'normal')
            {
                if($params['spec_type'] == 1)
                {
                    \app\admin\model\service\Goodsspu::where(['goods_id'=>$row->id,'status'=>'normal'])->update(['status'=>'hidden']);
                    \app\admin\model\service\Goodssku::where(['goods_id'=>$row->id,'status'=>'normal'])->update(['status'=>'hidden']);
                    $spuList = json_decode($params['spu'],true);

                    $spu = [];

                    foreach ($spuList as $value) {

                        $spu[] = [
                            'goods_id'	=> $row->id,
                            'name'		=> $value['name'],
                            'skudetail'=> implode(',',array_column($value['info'],'name'))
                        ];
                    }

                    if(!model('\app\admin\model\service\Goodsspu')->allowField(true)->saveAll($spu)){
                        $result == false;
                    }

                    $skuList = json_decode($params['sku'],true);
                    $sku = [];
                    foreach ($skuList  as $value) {

                        $sku[] = [
                            'goods_id' 		=> $row->id,
                            'name' 	        => $value['name'],
                            'cost_seconds'  => $value['cost_seconds'],
                            'price' 		=> $value['price'],
                        ];
                    }
                    if(!model('\app\admin\model\service\Goodssku')->allowField(true)->saveAll($sku)){
                        $result == false;
                    }
                }
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function updateGoodsStatus()
    {
        $id = input('id');
        $status = input('status');
        $goods = db('service_goods')->where('id',$id)->field('id,status')->find();
        $goods['status'] == $status && $this->error('商品状态错误');
        db('service_goods')->where('id',$id)->update(['status'=>$status]);
        $this->success('商品状态已更新');
    }

    public function select()
    {
        $params = (array)$this->request->request("custom/a");
        if (isset($params['pid'])) {
            $list = \app\admin\model\service\Category::where(['status'=>'normal','pid'=>$params['pid']])->field('id,name')->select();
        } else {
            $list = \app\admin\model\service\Category::where(['status'=>'normal','pid'=>0])->field('id,name')->select();
        }
        return json(['list' => $list, 'total' => count($list)]);
    }

    public function category()
    {

        $pid = $this->request->get('pid', '');
        $where = ['status' => 'normal'];
        $categorylist = null;
        if ($pid) {
            $where['pid'] = $pid;
        }else{
            $where['pid'] = 0;
        }
        $categorylist = Db::name('service_category')->where($where)->field('id as value,pid,name')->order('weigh desc,id desc')->select();

        $this->success('', '', $categorylist);
    }

}
